<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link href="https://cdn.bootcdn.net/ajax/libs/nprogress/0.2.0/nprogress.css" rel="stylesheet">
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
    <script src="https://cdn.bootcdn.net/ajax/libs/nprogress/0.2.0/nprogress.js"></script>
</head>

<body>
    <h1>取消请求</h1>
    <input type="text" id="ipt">
    <button id="btn">提交</button>
    <button id="cancel">取消请求</button>
    <script>
        let myaxios = axios.create({
            baseURL: '/',
            timeout: 10000,
            headers: {}
        })
        
        let ipt = document.querySelector('#ipt')
        let btn = document.querySelector('#btn')
        let Cancel = document.querySelector('#cancel')

        //拿到一个取消请求的对象(是一个构造函数)
        let CancelToken = axios.CancelToken
        let cancel = null
        btn.onclick = async function () {
            try {
                let result = await myaxios.get('/userdelay', {
                    params: {
                        userid: ipt.value
                    }, //在配置对象中配置一个cancelToken的配置项,值是实例化的CancelToken对象
                    cancelToken: new CancelToken((c) => {
                        console.log(c);
                        cancel = c
                        //一旦请求被中断,则交给catch处理这个异常                   
                    })
                })
                console.log(result);
            } catch(e){
                console.log(e.message,'出现错误');
            }           
        }
        Cancel.onclick = function(){
            cancel()
        }
    </script>
</body>

</html>